<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        body {
            position: relative;
        }

        #box {
            width: 100px;
            height: 100px;
            background-image: linear-gradient(135deg, #99bdb5, #37b9e9);
            position: absolute;
            left: 10px;
            top: 40px;
        }
    </style>
</head>

<body>
    <h3>点击WSAD移动盒子</h3>
    <div id="box"></div>
    <script>
        let box = document.getElementById('box');
        //为document绑定一个按键按下的事件
        let x = 10;
        y = 40;
        document.onkeydown = function (event) {
            switch (event.key) {
                case 'a':
                case 'A':
                    //'向左'
                    x -= 5;
                    break;
                case "d":
                case "D":
                    //"向右";
                    x += 5;
                    break;
                case 'w':
                case 'W':
                    //"向上"
                    y -= 5;
                    break;
                case 's':
                case 'S':
                    //'向下';
                    y += 5;
                    break;
            }
            if (x < 0) {
                x = 0;
            }
            if (y < 0) {
                y = 0;
            }
            if (x > innerWidth - box.offsetWidth) {
                x = innerWidth - box.offsetWidth
            }
            if (y > innerHeight - box.offsetHeight) {
                y = innerHeight - box.offsetHeight
            }
            box.style.cssText =
                `left:${x}px;
            top:${y}px`

        };
    </script>
</body>

</html>